// 第10关平衡性修复 - 激光器伤害调整和BOSS变身无敌时间
(function() {
    'use strict';
    
    console.log('🎯 第10关平衡性修复加载...');
    
    class Level10BalanceFix {
        constructor() {
            this.applied = false;
            this.originalLaserDamage = null;
            this.bossInvulnerabilityDuration = 2000; // 2秒无敌时间
            
            this.initialize();
        }
        
        initialize() {
            // 等待游戏系统加载完成
            setTimeout(() => {
                this.applyFixes();
            }, 3000);
        }
        
        applyFixes() {
            try {
                console.log('🔧 应用第10关平衡性修复...');
                
                // 1. 修复激光器伤害
                this.fixLaserDamage();
                
                // 2. 修复BOSS变身无敌时间
                this.fixBossInvulnerability();
                
                this.applied = true;
                console.log('✅ 第10关平衡性修复完成');
                
            } catch (error) {
                console.error('❌ 第10关平衡性修复失败:', error);
            }
        }
        
        fixLaserDamage() {
            try {
                // 检查Weapon类是否存在
                if (typeof Weapon === 'undefined') {
                    console.log('⚠️ Weapon类未找到，跳过激光器修复');
                    return;
                }
                
                // 保存原始的getWeaponStats方法
                if (Weapon.prototype.getWeaponStats && !this.originalGetWeaponStats) {
                    this.originalGetWeaponStats = Weapon.prototype.getWeaponStats;
                    
                    // 重写getWeaponStats方法
                    Weapon.prototype.getWeaponStats = function(type) {
                        const stats = this.originalGetWeaponStats ? 
                            this.originalGetWeaponStats.call(this, type) : 
                            this.getOriginalWeaponStats(type);
                        
                        // 如果是激光器，降低伤害
                        if (type === 'laser') {
                            const originalDamage = stats.damage;
                            stats.damage = 25; // 从45降到25
                            
                            if (window.level10BalanceFix && !window.level10BalanceFix.originalLaserDamage) {
                                window.level10BalanceFix.originalLaserDamage = originalDamage;
                                console.log(`🔫 激光器伤害已调整: ${originalDamage} → ${stats.damage}`);
                            }
                        }
                        
                        return stats;
                    };
                    
                    // 确保能访问原始方法
                    Weapon.prototype.getOriginalWeaponStats = this.originalGetWeaponStats;
                }
                
                // 更新现有的激光武器实例
                this.updateExistingLaserWeapons();
                
                console.log('✅ 激光器伤害修复完成');
                
            } catch (error) {
                console.error('❌ 激光器伤害修复失败:', error);
            }
        }
        
        updateExistingLaserWeapons() {
            try {
                // 更新玩家当前激光武器
                if (window.player && window.player.currentWeapon && window.player.currentWeapon.type === 'laser') {
                    const oldDamage = window.player.currentWeapon.damage;
                    window.player.currentWeapon.damage = 25;
                    window.player.currentWeapon.weaponStats.damage = 25;
                    console.log(`🔫 玩家激光器伤害已更新: ${oldDamage} → 25`);
                }
                
                // 更新掉落的激光武器
                if (window.gameEngine && window.gameEngine.weapons) {
                    window.gameEngine.weapons.forEach(weapon => {
                        if (weapon.type === 'laser') {
                            weapon.damage = 25;
                            weapon.weaponStats.damage = 25;
                        }
                    });
                }
                
            } catch (error) {
                console.error('更新现有激光武器失败:', error);
            }
        }
        
        fixBossInvulnerability() {
            try {
                // 检查Boss类是否存在
                if (typeof Boss === 'undefined') {
                    console.log('⚠️ Boss类未找到，跳过BOSS无敌修复');
                    return;
                }
                
                // 保存原始的checkPhaseTransition方法
                if (Boss.prototype.checkPhaseTransition && !this.originalCheckPhaseTransition) {
                    this.originalCheckPhaseTransition = Boss.prototype.checkPhaseTransition;
                    
                    // 重写checkPhaseTransition方法
                    Boss.prototype.checkPhaseTransition = function() {
                        const healthPercent = this.health / this.maxHealth;
                        const oldPhase = this.phase;
                        
                        // 调用原始方法
                        if (window.level10BalanceFix.originalCheckPhaseTransition) {
                            window.level10BalanceFix.originalCheckPhaseTransition.call(this);
                        }
                        
                        // 如果阶段发生了变化，添加无敌时间
                        if (this.phase !== oldPhase) {
                            this.startPhaseTransitionInvulnerability();
                        }
                    };
                    
                    // 添加阶段转换无敌方法
                    Boss.prototype.startPhaseTransitionInvulnerability = function() {
                        console.log(`🛡️ BOSS进入第${this.phase}阶段，获得${window.level10BalanceFix.bossInvulnerabilityDuration/1000}秒无敌时间`);
                        
                        // 设置无敌状态
                        this.isInvulnerable = true;
                        this.isPhaseTransitioning = true;
                        
                        // 视觉效果 - 金光闪烁
                        this.createPhaseTransitionEffect();
                        
                        // 设置定时器结束无敌
                        setTimeout(() => {
                            this.isInvulnerable = false;
                            this.isPhaseTransitioning = false;
                            console.log('🗡️ BOSS无敌时间结束');
                        }, window.level10BalanceFix.bossInvulnerabilityDuration);
                    };
                    
                    // 添加阶段转换特效方法
                    Boss.prototype.createPhaseTransitionEffect = function() {
                        try {
                            if (window.gameEngine && window.gameEngine.particles) {
                                // 创建金色粒子环
                                for (let i = 0; i < 20; i++) {
                                    const angle = (Math.PI * 2 / 20) * i;
                                    const radius = 60;
                                    
                                    window.gameEngine.particles.push({
                                        x: this.x + Math.cos(angle) * radius,
                                        y: this.y + Math.sin(angle) * radius,
                                        vx: Math.cos(angle) * 50,
                                        vy: Math.sin(angle) * 50,
                                        life: 2,
                                        maxLife: 2,
                                        color: '#FFD700',
                                        size: Math.random() * 6 + 4
                                    });
                                }
                                
                                // 创建向上升起的光芒
                                for (let i = 0; i < 15; i++) {
                                    window.gameEngine.particles.push({
                                        x: this.x + (Math.random() - 0.5) * 40,
                                        y: this.y + (Math.random() - 0.5) * 40,
                                        vx: (Math.random() - 0.5) * 30,
                                        vy: -Math.random() * 100 - 50,
                                        life: 3,
                                        maxLife: 3,
                                        color: '#FFFFFF',
                                        size: Math.random() * 4 + 2
                                    });
                                }
                            }
                        } catch (error) {
                            console.error('创建阶段转换特效失败:', error);
                        }
                    };
                    
                    // 增强原有的render方法以显示无敌状态
                    if (Boss.prototype.render && !this.originalBossRender) {
                        this.originalBossRender = Boss.prototype.render;
                        
                        Boss.prototype.render = function(ctx) {
                            // 调用原始渲染
                            window.level10BalanceFix.originalBossRender.call(this, ctx);
                            
                            // 如果在阶段转换中，添加金色光环
                            if (this.isPhaseTransitioning) {
                                ctx.save();
                                ctx.translate(this.x, this.y);
                                
                                // 金色闪烁光环
                                const alpha = 0.3 + Math.sin(Date.now() * 0.01) * 0.2;
                                ctx.globalAlpha = alpha;
                                ctx.strokeStyle = '#FFD700';
                                ctx.lineWidth = 4;
                                ctx.beginPath();
                                ctx.arc(0, 0, this.radius + 10, 0, Math.PI * 2);
                                ctx.stroke();
                                
                                // 无敌文字提示
                                ctx.globalAlpha = 1;
                                ctx.fillStyle = '#FFD700';
                                ctx.font = 'bold 14px monospace';
                                ctx.textAlign = 'center';
                                ctx.fillText('变身中...', 0, -this.radius - 20);
                                
                                ctx.restore();
                            }
                        };
                    }
                }
                
                console.log('✅ BOSS变身无敌时间修复完成');
                
            } catch (error) {
                console.error('❌ BOSS变身无敌时间修复失败:', error);
            }
        }
        
        // 创建屏幕提示
        showBalanceInfo() {
            const info = document.createElement('div');
            info.style.cssText = `
                position: fixed; top: 50px; left: 50%; transform: translateX(-50%);
                background: rgba(0, 0, 0, 0.8); color: #FFD700; padding: 15px 20px;
                border-radius: 8px; z-index: 10000; font-family: monospace;
                border: 2px solid #FFD700; text-align: center;
            `;
            info.innerHTML = `
                <div style="font-size: 16px; font-weight: bold; margin-bottom: 8px;">🎯 第10关已优化</div>
                <div style="font-size: 12px;">🔫 激光器伤害: 45 → 25</div>
                <div style="font-size: 12px;">🛡️ BOSS变身时获得2秒无敌时间</div>
            `;
            
            document.body.appendChild(info);
            
            // 5秒后自动消失
            setTimeout(() => {
                info.style.opacity = '0';
                setTimeout(() => {
                    if (info.parentNode) {
                        document.body.removeChild(info);
                    }
                }, 500);
            }, 5000);
        }
        
        // 监控第10关开始
        monitorLevel10() {
            setInterval(() => {
                try {
                    if (window.levelManager && 
                        window.levelManager.currentLevel === 10 && 
                        window.gameEngine && 
                        window.gameEngine.gameState === 'playing') {
                        
                        if (!this.level10InfoShown) {
                            this.showBalanceInfo();
                            this.level10InfoShown = true;
                        }
                    } else if (window.levelManager && window.levelManager.currentLevel !== 10) {
                        this.level10InfoShown = false;
                    }
                } catch (error) {
                    // 静默处理
                }
            }, 2000);
        }
        
        getStatus() {
            return {
                applied: this.applied,
                originalLaserDamage: this.originalLaserDamage,
                newLaserDamage: 25,
                bossInvulnerabilityDuration: this.bossInvulnerabilityDuration
            };
        }
    }
    
    // 全局初始化
    try {
        window.level10BalanceFix = new Level10BalanceFix();
        
        // 开始监控第10关
        window.level10BalanceFix.monitorLevel10();
        
        console.log('✅ 第10关平衡性修复系统已加载');
        
        // 调试命令
        window.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.shiftKey && e.code === 'Digit0') {
                console.log('🎯 第10关平衡性状态:', window.level10BalanceFix.getStatus());
            }
        });
        
    } catch (error) {
        console.error('❌ 第10关平衡性修复系统加载失败:', error);
    }
    
})();